<?php

namespace App\Policies;

use App\Models\AfterSalesRequest;
use App\Models\User;
use Illuminate\Auth\Access\HandlesAuthorization;

class AfterSalesPolicy
{
    use HandlesAuthorization;

    /**
     * 确定用户是否可以查看售后申请
     */
    public function view(User $user, AfterSalesRequest $afterSalesRequest): bool
    {
        return $user->id === $afterSalesRequest->user_id;
    }

    /**
     * 确定用户是否可以创建售后申请
     */
    public function create(User $user, AfterSalesRequest $afterSalesRequest): bool
    {
        return $user->id === $afterSalesRequest->user_id;
    }

    /**
     * 确定用户是否可以更新售后申请
     */
    public function update(User $user, AfterSalesRequest $afterSalesRequest): bool
    {
        return $user->id === $afterSalesRequest->user_id;
    }

    /**
     * 确定用户是否可以取消售后申请
     */
    public function cancel(User $user, AfterSalesRequest $afterSalesRequest): bool
    {
        return $user->id === $afterSalesRequest->user_id && $afterSalesRequest->canCancel();
    }

    /**
     * 确定用户是否可以提交物流信息
     */
    public function submitLogistics(User $user, AfterSalesRequest $afterSalesRequest): bool
    {
        return $user->id === $afterSalesRequest->user_id 
            && $afterSalesRequest->status === 'approved'
            && in_array($afterSalesRequest->type, ['return', 'exchange']);
    }

    /**
     * 确定管理员是否可以管理售后申请
     */
    public function manage(User $user, AfterSalesRequest $afterSalesRequest): bool
    {
        return $user->hasRole('admin') || $user->hasRole('super_admin');
    }

    /**
     * 确定管理员是否可以审核售后申请
     */
    public function approve(User $user, AfterSalesRequest $afterSalesRequest): bool
    {
        return $this->manage($user, $afterSalesRequest) 
            && $afterSalesRequest->status === 'pending';
    }

    /**
     * 确定管理员是否可以拒绝售后申请
     */
    public function reject(User $user, AfterSalesRequest $afterSalesRequest): bool
    {
        return $this->manage($user, $afterSalesRequest) 
            && in_array($afterSalesRequest->status, ['pending', 'approved']);
    }

    /**
     * 确定管理员是否可以完成售后申请
     */
    public function complete(User $user, AfterSalesRequest $afterSalesRequest): bool
    {
        return $this->manage($user, $afterSalesRequest) 
            && $afterSalesRequest->status === 'processing';
    }
}